<?php
/***
 * handles user
 *
 *
 **/
session_start();

require_once 'db.php';
require_once 'thread.php'; // XXX this is because we need clean(), queries might need to sperated out later
require_once 'tpl.php';

if( !is_string($_REQUEST['type']) ) {
  // error BREAK
}

switch( $_REQUEST['type'] ) {
  case 'REGISTER':
    handleRegister(); break;
  case 'LOGIN':
    handleLogin(); break;
  case 'LOGOUT':
    handleLogout(); break;
  default:
    break;
}

tplHead();
echo <<<EOE
<a href="spit.php" >Thank You.</a>
EOE;
tplFoot();

function handleRegister() {
  if( is_string($_POST['user']) && is_string($_POST['pass']) 
      && is_string( $_POST['email'] ) ) {
    try {
      $db = openDbConn();

      // validate for spaces and stuff like that
      $user = $db->quote($_POST['user']);
      $pass = $db->quote(hash( 'sha512', ($_POST['pass']) ));
      $email = $db->quote($_POST['email']);

      $db->exec("INSERT INTO user (name, pass, mail) 
                    VALUES ($user, $pass, $email) ");
      } catch ( PDOException $e ) {
        print "ERROR: " . $e->getMessage() . "<br />";
        die();
      }
  } 
}
function handleLogin() {
  if( is_string($_POST['user']) && is_string($_POST['pass']) ) {
    try {
      $db = openDbConn();
      
      $user = $db->quote($_POST['user']);
      $pass = $db->quote(hash('sha512', $_POST['pass']));

      $res = $db->query("SELECT uid, name FROM user 
                    WHERE name = $user
                      AND pass = $pass");
      // TODO does this show success
      if( $res ) {
        $user = $res->fetch();
        $_SESSION['uid'] = $user['uid'];
        $_SESSION['user']['name'] = $user['name'];
        $res->closeCursor();
        $res = NULL;
        $loginSuccess = true;
      } else {
        $loginSuccess = false;
      }
    } catch ( PDOException $e ) {
      print "ERROR: " . $e->getMessage() . "<br />";
      die();
    }   
  }

  // TODO handle login output control $loginSuccess
}
function handleLogout() {
  session_destroy();
}
?>
